package com.press.controllers.admin;

import com.alibaba.fastjson.JSONObject;
import com.press.bean.TemplateBean;
import com.press.controllers.InitController;
import com.press.services.InitService;
import com.press.services.TemplateService;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * Created by dana on 2016/10/13.
 */
@Controller
@RequestMapping("/Template")
public class TemplateController {
    @Resource(name="templateService")
    private TemplateService templateService;
    private static Logger log = Logger.getLogger(PanelController.class);

    /**
     * 获得所有模板
     * @param request
     * @param response
     */
    @RequestMapping("/ShowAllTemplates")
    public void ShowAllTemplates(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<TemplateBean> templates=templateService.getalltemplates();
        TemplateBean isusetemplate=templateService.getusetemplate();
        log.info("************ShowAllTemplates");
        JSONObject json = new JSONObject();
        json.put("templates",templates);
        json.put("isusetemplate",isusetemplate);
        response.getWriter().print(json.toJSONString());
    }

    /**
     * 修改模板
     * @param request
     * @param response
     */
    @RequestMapping("/ChangeTemplate")
    public void ChangeTemplate(HttpServletRequest request,HttpServletResponse response) throws IOException {
        log.info("************ChangeTemplate");
        String template_id = request.getParameter("template_id");
        boolean result=templateService.changetemplate(template_id);
        JSONObject json=new JSONObject();
        json.put("result",result);
        InitController initController =(InitController) WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean("initController");
        initController.init(request.getServletContext());
        WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean("initController");
        response.getWriter().print(json.toJSONString());

    }

    /**
     * 添加新的模板
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/InstallTemplate")
    public void InstallTemplate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        log.info("*******************InstallTemplate");
        MultipartHttpServletRequest multipartrequest = (MultipartHttpServletRequest) request;
        MultipartFile afile = multipartrequest.getFile("uploadtemplatefile");
        String path = "/static/uploadfiles";
        path = request.getSession().getServletContext().getRealPath(path);
        File file=new File(path);
        if  (!file .exists()  && !file .isDirectory())
        {
            file.mkdir();
        }
        String filename=afile.getOriginalFilename().substring(0,afile.getOriginalFilename().lastIndexOf("."));
        int hassamename=templateService.ifHasSameName(filename);
        if(hassamename!=0){
            log.info("***************上传的zip文件与已有模板重名");
            request.setAttribute("infotittle","安装失败");
            request.setAttribute("infomassage","您上传的文件与已有模板重名");
            String url="/WEB-INF/admin/template/installinfo.jsp";
            request.getRequestDispatcher(url).forward(request,response);
        }
        filename=filename+".zip";
        String zipfilepath=path + File.separator + filename;
        FileOutputStream os = new FileOutputStream(zipfilepath);
        IOUtils.copy(afile.getInputStream(),os);
        os.flush();
        os.close();
        boolean fileisok=templateService.judgezip(zipfilepath);
        if(fileisok){
            log.info("***************上传的zip文件符合要求,开始解压");
            log.info("***************zipfilepath:"+zipfilepath);
            //String destdir=zipfilepath.substring(0,zipfilepath.lastIndexOf((File.separator+"Press"+File.separator)))+"\\Press\\web\\"+filename.substring(0,filename.lastIndexOf("."));
            String destdir = request.getServletContext().getRealPath("/");
            File destfile=new File(destdir);
            if  (!destfile .exists()  && !destfile .isDirectory())
            {
                destfile.mkdir();
            }
            String result = templateService.unZip(zipfilepath, destdir);
            if(result!=null){
                log.info("***************解压成功："+result);
                TemplateBean newtemplate=new TemplateBean();
                String enclosure= "/"+result;
                newtemplate.setTemplate_id(filename.substring(0,filename.lastIndexOf(".")));
                newtemplate.setTemplate_file(enclosure);
                String date=new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss").format(Calendar.getInstance().getTime());
                newtemplate.setTemplate_date(date);
                templateService.addtemplate(newtemplate);
                request.setAttribute("infotittle","安装成功");
                request.setAttribute("infomassage","恭喜您添加了一个新模板："+filename.substring(0,filename.lastIndexOf(".")));
                String url="/WEB-INF/admin/template/installinfo.jsp";
                request.getRequestDispatcher(url).forward(request,response);
            }else {
                log.info("***************解压失败");
                request.setAttribute("infotittle","安装失败");
                request.setAttribute("infomassage","解压失败");
                String url="/WEB-INF/admin/template/installinfo.jsp";
                request.getRequestDispatcher(url).forward(request,response);
            }
        }else{
            log.info("***************上传的zip文件不符合要求");
            request.setAttribute("infotittle","安装失败");
            request.setAttribute("infomassage","您上传的文件不符合要求");
            String url="/WEB-INF/admin/template/installinfo.jsp";
            request.getRequestDispatcher(url).forward(request,response);
        }


    }

    public TemplateService getTemplateService() {
        return templateService;
    }

    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }

}
